// pages/mine/mine.js
const app = getApp();
const promisify = require("../../utils/promisify")
const RESENDTIME = 60

Page({

  /**
   * 页面的初始数据
   */
  data: {
    loginCode: 0, //0为登录， 1为注册， 2为找回密码，3为已经登录，4为修改密码
    username: '',
    password: '',
    rPassword: '',
    telephone: '',
    code: '',
    resendTime: RESENDTIME,
    codeStatus: 0,
    getCodeText: "获取验证码",
    savePassword: false,
    onlineCount: 0
  },



  onLoad: function (data) {
    /**
     * 判断用户是否已经登录
     */
    let that = this
    let loginCode = app.globalData.loginCode
    that.setData({
      loginCode: loginCode
    })
    if (loginCode === 3) {
      that.hasLogin()
    }
  },



  hasLogin: function () {
    /**
     * 登录后请求的数据
     * 当前在线人数
     */
    let that = this
    promisify(wx.request)({
      url: `https://www.cumthing.world/cumthing/api/v1/online`,
      method: "GET",
      header: {
        Authorization: app.globalData.token
      }
    }).then(
      data => {
        that.setData({
          onlineCount: data.data.data
        })
      },
      reason => {
        console.log(reason)
      }
    )
  },



  change: function (e) {
    /**
     * 跳转页面，并且清除输入框对应的缓存数据
     */
    this.setData({
      loginCode: Number(e.target.dataset.data),
      username: '',
      password: '',
      code: '',
      telephone: '',
      rPassword: ''
    })
  },



  bindInput: function (e) {
    /**
     * 为输入框绑定数据
     */
    let data = e.target.dataset.data
    this.setData({
      [data]: e.detail.value
    })
  },



  logout: function () {
    /**
     * 退出登录
     */
    let that = this
    promisify(wx.showModal)({
      title: "是否确定退出登录",
      confirmText: "确定",
      cancelText: "取消"
    }).then(
      data => {
        if (data.confirm) {
          that.setData({
            loginCode: 0
          })
          //退出时发送的请求
          promisify(wx.request)({
            url: `https://www.cumthing.world/cumthing/api/v1/logout`,
            method: 'GET',
            header: {
              'Content-Type': 'application/json',
              'Authorization': app.globalData.token
            }
          }).then(
            data => {},
            reason => {console.log(reason)}
          )
          //本地设置
          app.changeGlobal("loginCode", 0)
          app.changeLocalAndGlobal("token", "")
          app.changeLocalAndGlobal("userId", undefined)
          app.changeLocalAndGlobal("userName", "")
          promisify(wx.setStorage)({
            key: "loginCode",
            data: 0
          }).then(
            data => {},
            err => {console.log(err)}
          )
        }
      },
      err => {}
    )
  },



  login: function () {
    /**
     * 发送用户名和密码到服务器，根据返回码，判断是否登录成功
     * 如果验证成功，更改本地缓存loginCode，？？要不要在本地记录用户名密码信息？？
     * 如果验证失败，则重新输入
     */
    let that = this
    if (that.checkUsername() && that.checkPassword()) {
      promisify(wx.request)({
        url: `https://www.cumthing.world/cumthing/api/v1/login`,
        method: "POST",
        data: {
          name: that.data.username,
          password: that.data.password,
          remFlag: Number(that.data.savePassword)
        }
      }).then(
        data => {
          data = data.data
          if (data.code === 0) {
            /**
             * 登录成功
             */
            that.setData({
              loginCode: 3
            })
            app.changeLocalAndGlobal("loginCode", 3)
            app.changeLocalAndGlobal("token", "Bearer " + data.data.token)
            app.changeLocalAndGlobal("userId", data.data.userDetail.id)
            app.changeLocalAndGlobal("userName", data.data.userDetail.username)
            if (that.data.savePassword) {
              that.save()
            }
            that.hasLogin()
          }
          if (data.code === 1002) {
            wx.showToast({
              title: data.message,
              icon: "none",
              duration: 2000
            })
          }
        },
        reason => {
          console.log(reason)
        }
      )
    }
  },



  changePassword: function () {
    /**
     * 修改密码
     */
    let that = this
    if (that.checkSamePassword()) {
      let url = `https://www.cumthing.world/cumthing/api/v1/change-secret` + app.ToParams({
        newpw: that.data.password
      })
      promisify(wx.request)({
        url: url,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': app.globalData.token
        }
      }).then(
        data => {
          if (data.data === "恭喜你密码修改成功") {
            wx.showToast({
              title: "修改成功",
              icon: "none",
              duration: 2000
            })
            that.setData({
              loginCode: 3
            })
          }
        }
      )
    }
  },



  save: function () {
    /**
     * 保存密码
     */
    let that = this
    app.changeLocal("username", that.data.username)
    app.changeLocal("password", that.data.password)
  },



  regist: function () {
    /**
     * 发送用户名和密码到服务器，根据返回码，判断是否注册成功
     * 如果注册成功，直接登录，更改本地缓存loginCode
     * 如果失败，重新注册
     */
    let that = this
    if (that.checkUsername() && that.checkPassword() && that.checkPhone() && that.checkCode()) {
      //如果输入没有问题
      let url = `https://www.cumthing.world/cumthing/api/v1/register` + app.ToParams({
        username: that.data.username,
        password: that.data.password,
        telephone: that.data.telephone,
        verify: that.data.code
      })
      promisify(wx.request)({
        url: url,
        method: "POST",
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }).then(
        data => {
          data = data.data
          if (data === "恭喜你已经成功注册") {
            /**
             * 注册成功
             * 跳转到登录界面
             */
            that.setData({
              loginCode: 0,
              username: '',
              password: '',
              getCodeText: "获取验证码",
              codeStatus: 0,
              resendTime: RESENDTIME
            })
          } else if (data.code === 1000) {
            /**
             * 验证码错误
             */
            wx.showToast({
              title: "验证码错误!",
              icon: "none",
              duration: 2000
            })
          } else if (data.code === 1003) {
            wx.showToast({
              title: "用户已存在",
              icon: "none",
              duration: 2000
            })
          }
        },
        reason => {
          console.log(reason)
        }
      )
    }
  },



  forgetPassword: function () {
    /**
     * 忘记密码
     */
    let that = this
    if (that.checkPhone() && that.checkPassword() && that.checkCode()) {
      let url = `https://www.cumthing.world/cumthing/api/v1/forget-secret` + app.ToParams({
        telephone: that.data.telephone,
        ver: that.data.code,
        newpw: that.data.password
      })
      promisify(wx.request)({
        url: url,
        method: "POST"
      }).then(
        data => {
          if (data.data === "恭喜你密码修改成功") {
            wx.showToast({
              title: "修改成功",
              icon: "none",
              duration: 2000
            })
            that.setData({
              loginCode: 0
            })
          } else {
            wx.showToast({
              title: "修改失败",
              icon: "none",
              duration: 2000
            })
          }
        }
      )
    }
  },



  getCode: function () {
    /**
     * 发送验证码函数
     * 当填写手机号，且codeStatus状态为0时发送请求，并且改变codeStatus状态为1，表示正在发送
     */
    let that = this
    let codeStatus = that.data.codeStatus
    if (codeStatus != 1 && that.checkPhone()) {
      //sendRequest
      that.sendVertifyCode()
    }
  },



  sendVertifyCode: function () {
    /**
     * 发送验证码
     * 首先判断是否输入正确的手机号
     * 正确就发送，不正确就提醒
     */
    let that = this
    let telephone = that.data.telephone
    let params = app.ToParams({
      telephone: telephone
    })
    let url =  `https://www.cumthing.world/cumthing/api/v1/verify` + params
    if (that.checkPhone()) {
      promisify(wx.request)({
        url: url,
        method: "POST"
      }).then(
        data => {
          that.resend()
        }
      )
    }
  },



  resend: function () {
    /**
     * 读秒函数
     * 60秒后可以重新发送
     */
    let that = this
    let codeStatus = that.data.codeStatus
    let resendTime = that.data.resendTime
    let getCodeText = resendTime + "秒后重新发送"
    if (codeStatus != 1) {
      that.setData({
        codeStatus: 1,
        resendTime: --resendTime,
        getCodeText: getCodeText
      })
      let timer = setInterval(() => {
        resendTime = that.data.resendTime
        getCodeText = resendTime + "秒后重新发送"
        if (resendTime > 0) {
          that.setData({
            resendTime: --resendTime,
            getCodeText: getCodeText
          })
        } else if (resendTime === 0) {
          that.setData({
            codeStatus: 2,
            resendTime: RESENDTIME,
            getCodeText: "重新发送"
          })
          clearInterval(timer)
        }
      }, 1000);
    }
  },



  remember: function () {
    let that = this
    let checked = !that.data.checked
    that.setData({
      checked
    })
  },



  checkUsername: function () {
    if (this.data.username === '') {
      wx.showToast({
        title: '请输入用户名！',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    return true
  },



  checkPassword: function () {
    if (this.data.password.length < 8) {
      wx.showToast({
        title: '密码至少为8位！',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    return true
  },



  checkCode: function () {
    if (this.data.code.length !== 6) {
      wx.showToast({
        title: '请输入完整的验证码',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    return true
  },



  checkPhone: function () {
    var reg = /^((1[3-9][0-9])+\d{8})$/;
    if (!reg.test(this.data.telephone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    return true
  },



  checkSamePassword: function () {
    let that = this
    if (!that.checkPassword()) {
      return false
    } else {
      if (!(that.data.password === that.data.rPassword)) {
        wx.showToast({
          title: '两次密码不相同',
          icon: 'none',
          duration: 2000
        })
        return false
      }
    }
    return true
  }
})